package cn.tedu.cake.shop.product.service.impl;

import cn.tedu.cake.shop.product.ex.ServiceException;
import cn.tedu.cake.shop.product.mapper.BreadMapper;
import cn.tedu.cake.shop.product.pojo.entity.Bread;
import cn.tedu.cake.shop.product.pojo.param.BreadAddNewParam;
import cn.tedu.cake.shop.product.service.BreadService;
import cn.tedu.cake.shop.product.web.ServiceCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class BreadServiceImpl implements BreadService {

    @Autowired
    BreadMapper breadMapper;

    @Override
    public void addNew(BreadAddNewParam breadAddNewParam) {
        log.debug("开始处理【添加面包】的业务，参数：{}",breadAddNewParam);
        //检查面包标题有没有被占用，若被占用，则抛出异常
        QueryWrapper<Bread> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",breadAddNewParam.getTitle());
        int countByTitle = breadMapper.selectCount(queryWrapper);
        log.debug("根据面包标题配置面包的数量：{}",countByTitle);
        if (countByTitle > 0){
            String message = "添加面包失败，面包标题已被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //开始添加面包
        Bread bread = new Bread();
        BeanUtils.copyProperties(breadAddNewParam,bread);
        bread.setSaleCount(0);
        bread.setGmtCreate(LocalDateTime.now());
        bread.setGmtModified(LocalDateTime.now());
        breadMapper.insert(bread);
    }
}
